﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.Entity.Entity.JJFlow;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Core.UnitOfWork.UnitOfWorkComponent;
using SqlSugar;

namespace Jinjia.Approve.Repository.JJFlow
{
    public class FlowInstanceFormRepository : IFlowInstanceFormRepository
    {
        private readonly ISqlSugarClient _db;

        public FlowInstanceFormRepository(IUnitOfWork unitOfWork)
        {
            _db = unitOfWork.GetDbClient();
        }

        public async Task Save(List<jj_flow_instance_form> data)
        {
            var jjFlowInstanceForms = data.Where(x => x.id <= 0).ToList();

            if (jjFlowInstanceForms.Any())
            {
                await _db.Insertable(jjFlowInstanceForms).ExecuteCommandAsync();
            }

            var flowInstanceForms = data.Where(x => x.id > 0).ToList();
            if (flowInstanceForms.Any())
            {
                await _db.Updateable(flowInstanceForms).ExecuteCommandAsync();
            }
        }

        public async Task<string> GetValueByKey(int instance_id, string form_key)
        {
            var value = await _db.Queryable<jj_flow_instance_form>()
                .Where(a => a.instance_id == instance_id && a.form_key == form_key).Select<string>(a => a.form_value)
                .FirstAsync();
            return value;
        }

        public async Task<jj_flow_instance_form> GetModelByKey(int instance_id, string form_key)
        {
            var model = await _db.Queryable<jj_flow_instance_form>()
                .Where(a => a.instance_id == instance_id && a.form_key == form_key)
                .FirstAsync();
            return model;
        }

        public async Task<List<jj_flow_instance_form>> GetListByInstanceId(int instanceId) => await _db.Queryable<jj_flow_instance_form>().Where(x => x.instance_id == instanceId).ToListAsync();
    }
}